﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XXX.Common
{
    public class CacheHelpCore
    {
        private static MemoryCache cache = new MemoryCache(new MemoryCacheOptions()); //定义cache
        public static object GetCacheValue(string key)//获取值
        {
            object val = null;
            if (key != null && cache.TryGetValue(key, out val))
            {
                return val;
            }
            else
            {
                return default(object);
            }
        }
        public static void SetChacheValue(string key, object value)//设置值
        {
            if (key != null)
            {
                cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromSeconds(10)
                });
            }
        }

        public static void SetChacheValue(string key, object value, double Seconds)//设置值
        {
            if (key != null)
            {
                cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    //第一次缓存超时
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(Seconds),
                    ////最近一次调用超时
                    //SlidingExpiration = TimeSpan.FromSeconds(Seconds)
                });
            }
        }

        //定时清理缓存
        public static void CleanupCache()
        {
            cache.Compact(1.0);
            //var cacheEntriesCollection = new List<KeyValuePair<object, object>>();
            //var cacheEntries = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(cache) as System.Collections.ICollection;

            //foreach (var cacheItem in cacheEntries)
            //{
            //    var key = cacheItem.GetType().GetProperty("Key").GetValue(cacheItem);
            //    var value = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem);
            //    cacheEntriesCollection.Add(new KeyValuePair<object, object>(key, value));
            //}

            //foreach (var cacheEntry in cacheEntriesCollection)
            //{
            //    var cacheEntryOptions = cacheEntry.Value.GetType().GetProperty("Options").GetValue(cacheEntry.Value) as MemoryCacheEntryOptions;
            //    if (cacheEntryOptions != null && cacheEntryOptions.AbsoluteExpirationRelativeToNow.HasValue)
            //    {
            //        var expirationTime = DateTime.UtcNow.Add(cacheEntryOptions.AbsoluteExpirationRelativeToNow.Value);
            //        if (expirationTime < DateTime.UtcNow.AddDays(-1))
            //        {
            //            cache.Remove(cacheEntry.Key);
            //        }
            //    }
            //}
        }

    }
}